package com.neuedu.yyzx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.yyzx.common.Ret;
import com.neuedu.yyzx.dto.CustomerNurseItemDTO;
import com.neuedu.yyzx.dto.CustomerNurseSetDTO;
import com.neuedu.yyzx.mapper.CustomernurseitemMapper;
import com.neuedu.yyzx.po.*;
import com.neuedu.yyzx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/customernurseitem"})
public class CustomerNurseItemController {
    @Autowired
    private CustomernurseitemService customernurseitemService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private NurselevelitemService nurselevelitemService;
    @Autowired
    private NurserecordService nurserecordService;

    @Autowired
    private NursecontentService nursecontentService;

    @Autowired
    private CustomernurseitemMapper customernurseitemMapper;

    @GetMapping("/list")
    public Ret<Page<CustomerNurseSetDTO>> list(Page<CustomerNurseSetDTO> page) {
        // 调用service层方法，获取分页数据并包含nickname和level_name
        return Ret.ok(customerService.pageWithDetails(page, null));
    }

    @GetMapping("/page")
    public Ret<Page<CustomerNurseSetDTO>> page(Page<CustomerNurseSetDTO> page, Customer customer) {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        if (customer.getCustomerName() != null && !customer.getCustomerName().trim().isEmpty()) {
            String trimmedName = customer.getCustomerName().trim();
            queryWrapper.like(Customer::getCustomerName, trimmedName);
        }
        // 删除多余的 orderBy 条件，避免与动态 SQL 冲突
        // queryWrapper.orderByDesc(Customer::getCheckinDate);
        page = customerService.pageWithDetails(page, queryWrapper);

        return Ret.ok(page);
    }


    @GetMapping("/listitem")
    public Ret<List<CustomerNurseItemDTO>> listItem(Page<CustomerNurseItemDTO> page, Customer customer) {
        String searchName = customer.getCustomerName();
        if (searchName != null && !searchName.trim().isEmpty()) {
            String trimmedName = searchName.trim();
            LambdaQueryWrapper<Customer> customerQueryWrapper = new LambdaQueryWrapper<>();
            customerQueryWrapper.like(Customer::getCustomerName, trimmedName);
            List<Integer> customerIds = customerService.list(customerQueryWrapper).stream()
                    .map(Customer::getCustomerId)
                    .collect(Collectors.toList());

            LambdaQueryWrapper<Customernurseitem> queryWrapper = new LambdaQueryWrapper<>();
            if (!customerIds.isEmpty()) {
                queryWrapper.in(Customernurseitem::getCustomerId, customerIds); // 动态拼接 IN 条件
            } else {
                // 如果没有匹配的客户ID，返回空结果
                return Ret.ok(new Page<>());
            }
            System.out.println("queryWrapper:" + queryWrapper.getSqlSelect());
            page = customernurseitemService.pageDetails(page, queryWrapper);
            return Ret.ok(page);
        } else {
            // 如果 searchName 为空，返回所有数据
            LambdaQueryWrapper<Customernurseitem> queryWrapper = new LambdaQueryWrapper<>();
            page = customernurseitemService.pageDetails(page, queryWrapper);
            return Ret.ok(page);
        }
    }

    @GetMapping("/pageToday")
    public Ret<Page<CustomerNurseItemDTO>> pageToday(Page<CustomerNurseItemDTO> page, Customer customer) {
        String searchName = customer.getCustomerName();
        if (searchName != null && !searchName.trim().isEmpty()) {
            String trimmedName = searchName.trim();
            LambdaQueryWrapper<Customer> customerQueryWrapper = new LambdaQueryWrapper<>();
            customerQueryWrapper.like(Customer::getCustomerName, trimmedName);
            List<Integer> customerIds = customerService.list(customerQueryWrapper).stream()
                    .map(Customer::getCustomerId)
                    .collect(Collectors.toList());

            LambdaQueryWrapper<Customernurseitem> queryWrapper = new LambdaQueryWrapper<>();
            if (!customerIds.isEmpty()) {
                queryWrapper.in(Customernurseitem::getCustomerId, customerIds); // 动态拼接 IN 条件
                System.out.println("customerIds:" + customerIds);
            } else {
                return Ret.ok(new Page<>());
            }

            // 合并到同一 queryWrapper：先按客户名查，再加 maturity_time 过滤
            queryWrapper.gt(Customernurseitem::getMaturityTime, new java.util.Date());
            page = customernurseitemService.pageDetails(page, queryWrapper); // 只调用一次分页查询

            return Ret.ok(page);
        } else {
            // 如果 searchName 为空，只按日期过滤即可
            LambdaQueryWrapper<Customernurseitem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.gt(Customernurseitem::getMaturityTime, new java.util.Date()); // maturity_time大于当前日期的记录
            page = customernurseitemService.pageDetails(page, queryWrapper);
            return Ret.ok(page);
        }
    }

    @GetMapping("/getbyid/{id}")
    public Ret<Map<String, Object>> getById(@PathVariable("id") int id) {
        System.out.println("id:" + id);
        try {
//            人的护理记录
            Customernurseitem result = customernurseitemService.getById(id);
            Customer customer = customerService.getById(result.getCustomerId());
//          护理项目基础信息
            Nursecontent nursecontent = nursecontentService.getById(result.getItemId());

            Map<String, Object> map = new HashMap<>();
            map.put("customernurseitem", result);
            map.put("customer", customer);
            map.put("nursecontent", nursecontent);
            return Ret.ok(map);
        } catch (Exception e) {
            // 处理异常，例如返回错误响应
            return Ret.error("Error retrieving data: " + e.getMessage());
        }
    }

    @PostMapping("/addset")
    public Ret<Boolean> addNurseItems(@RequestBody Customernurseitem customernurseitem) {
        System.out.println("ccccc" + customernurseitem);
        customernurseitem.setIsDeleted(0);
        customernurseitemService.saveOrUpdate(customernurseitem);
        return Ret.ok(true);
    }

    @PostMapping("/saveorupdate")
    public Ret<Boolean> saveOrUpdate(@RequestBody Customer newCustomer) {
        // 调用service层保存或更新customer信息
        Customer oldCustomer = customerService.getById(newCustomer.getCustomerId());
        Integer userId = newCustomer.getUserId();
        System.out.println("newuserId: " + userId);
        Integer oldLevelId = oldCustomer.getLevelId();
        System.out.println("oldLevelId: " + oldLevelId);
        if (oldLevelId == null) {
            // 添加护理项目配置
            addNurseItems(oldCustomer, newCustomer.getLevelId(), userId);
        } else if (!oldLevelId.equals(newCustomer.getLevelId())) {
            // 删除老护理配置
            LambdaQueryWrapper<Customernurseitem> queryWrapper0 = new LambdaQueryWrapper<>();
            queryWrapper0.eq(Customernurseitem::getCustomerId, newCustomer.getCustomerId());
            List<Integer> ids = customernurseitemService.list(queryWrapper0).stream()
                    .map(Customernurseitem::getId)
                    .collect(Collectors.toList());
            if (!ids.isEmpty()) {
                customernurseitemService.removeBatchByIds(ids);
                // 添加新护理项目配置
                addNurseItems(oldCustomer, newCustomer.getLevelId(), userId);
            }
        }

        return Ret.ok(true);
    }

    @PostMapping("/update")
    public Ret<Boolean> update(@RequestBody Customernurseitem newcustomer) {
        boolean success = customernurseitemService.updateById(newcustomer);
        return Ret.ok(success);
    }

    @PostMapping("/updateadd")
    public Ret<Boolean> updateadd(@RequestBody Customernurseitem customernurseitem) {
        // C检查项目更新前是否存在
//        Customernurseitem existingItem = customernurseitemService.getById(customernurseitem.getId());
//        if (existingItem == null) {
//            return Ret.error("Customernurseitem not found with id: " + customernurseitem.getId());
//        }

        // 更新customernurseitem
        boolean success = customernurseitemService.save(customernurseitem);
        if (success) {
            return Ret.ok(true);
        } else {
            return Ret.error("Failed to update customernurseitem with id: " + customernurseitem.getId());
        }
    }

    @PostMapping("/doneNursing")
    public Ret<Boolean> doneNursing(@RequestBody Nurserecord record) {
        Integer customerId = record.getCustomerId();
        Customer customer = customerService.getById(customerId);
        Integer userId = customer.getUserId();
        record.setId(null);
        record.setUserId(userId);
        return Ret.ok(nurserecordService.saveOrUpdate(record));
    }

    @DeleteMapping("/{id}")
    public Ret<Boolean> delete(@PathVariable int id) {
        // 调用service层删除customer信息
        Customer oldCustomer = customerService.getById(id);

        // 删除关联的护理项目
        LambdaQueryWrapper<Customernurseitem> queryWrapper0 = new LambdaQueryWrapper<>();
        queryWrapper0.eq(Customernurseitem::getCustomerId, id);
        List<Integer> ids = customernurseitemService.list(queryWrapper0).stream()
                .map(Customernurseitem::getId)
                .collect(Collectors.toList());
        if (!ids.isEmpty()) {
            customernurseitemService.removeBatchByIds(ids);
        }

        // 使用 UpdateWrapper 显式设置 levelId 和 userId 为 null
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("level_id", null)
                .set("user_id", null)
                .eq("customer_id", id)
                .eq("is_deleted", 0);

        // 执行更新操作
        boolean updateResult = customerService.update(updateWrapper);

        // 增加日志记录，确认更新结果
        if (updateResult) {
            System.out.println("Customer updated successfully with levelId and userId set to null.");
        } else {
            System.out.println("Failed to update customer with levelId and userId set to null.");
        }

        return Ret.ok(true);
    }
    @DeleteMapping("/deleteitem/{id}")
    public Ret<Boolean> deleteItem(@PathVariable int id) {
        // 调用service层删除customer信息
        customernurseitemService.removeById(id);
        return Ret.ok(true);
    }


    @DeleteMapping("deleteById/{id}")
    public Ret<Boolean> deleteById(@PathVariable int id) {
        return Ret.ok(customernurseitemService.removeById(id));
    }

    /**
     * 添加护理项目配置
     *
     * @param customer 老客户对象
     * @param levelId  新等级ID
     * @param userId   新用户ID
     */
    private void addNurseItems(Customer customer, Integer levelId, Integer userId) {
        LambdaQueryWrapper<Nurselevelitem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Nurselevelitem::getLevelId, levelId);
        List<Integer> itemIds = nurselevelitemService.list(queryWrapper).stream()
                .map(Nurselevelitem::getItemId)
                .collect(Collectors.toList());
        if (itemIds != null && !itemIds.isEmpty()) {
            for (Integer itemId : itemIds) {
                // 构造customernurseitem数据并更新
                Customernurseitem customernurseitem = new Customernurseitem();
                customernurseitem.setCustomerId(customer.getCustomerId());
                customernurseitem.setLevelId(levelId);
                customernurseitem.setItemId(itemId);
                customernurseitem.setNurseNumber(1); // 默认值为1
                customernurseitem.setIsDeleted(0);
                customernurseitem.setBuyTime(new java.sql.Timestamp(System.currentTimeMillis())); // 当前时间
                customernurseitem.setMaturityTime(customer.getExpirationDate()); // 设置到期时间
                customernurseitemService.saveOrUpdate(customernurseitem);
            }
        }
        customer.setUserId(userId);
        customer.setLevelId(levelId);
        customerService.updateById(customer);
    }

    @GetMapping("/details")
    public Ret<Page<CustomerNurseItemDTO>> customerNurseItemDetails(Page<CustomerNurseItemDTO> page, @RequestParam(value = "customerName", required = false) String customerName) {
        Page<CustomerNurseItemDTO> resultPage = (Page<CustomerNurseItemDTO>) customernurseitemMapper.selectCustomerNurseItemDetails(page, customerName);
        return Ret.ok(resultPage);
    }
}
